<script setup>
import {Edit} from "@element-plus/icons-vue";
import {computed, reactive, ref} from "vue";
import {Delta, Quill, QuillEditor} from "@vueup/vue-quill";
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {Check} from "@element-plus/icons-vue/global";
import ImageResize from 'quill-image-resize-vue';
import { ImageExtend, QuillWatch } from 'quill-image-super-solution-module';
import axios from "axios";
import {accessHeader, get, post} from "@/net/index.js";
import {ElMessage} from "element-plus";
import ColorDot from "@/componments/ColorDot.vue";
import dalta from "quill-image-resize-vue";
import {useStore} from "vuex";
Quill.register('modules/imageResize', ImageResize)
Quill.register('modules/ImageExtend', ImageExtend)
const editor = reactive({
  type:null,
  title:'',
  text:'',
  loading :false,
  types_com:[],
  types: [],
  uploading:false,
  selectedType:null
})
const props = defineProps({
  show: Boolean,
  defaultTitle: {
    default: '',
    type: String
  },
  defaultText: {
    default: '',
    type: String
  },
  defaultType: {
    default: null,
    type: Number
  },
  submitButton: {
    default: '立即发表主题',
    type: String
  },
  selectType:{
    default: null,
    type:Number
  },
  submitClick:{
    default: (editor,success) =>{
      console.log(editor.type)
      post("api/forum/create-topic", {
      type: editor.type,
      title: editor.title,
      content: editor.text
}, () => {
  ElMessage.success('发表帖子成功');
  console.log("emit success")
  success()
})
    } ,
    type: Function
  }
})
const store = useStore()
const emit = defineEmits(['close','success'])

function initEditor() {
  if(props.defaultText)
    editor.text = new Delta(JSON.parse(props.defaultText))
  else   textRef.value.setContents('','user')



  editor.type = props.defaultType;
  editor.title = props.defaultTitle;
  editor.types = store.state.forum.types
  editor.selectedType = handleTypeChange2(editor.type);
  console.log(editor.selectedType)
}
function detalTotext(delta){
  if(!delta.ops) return ''
  let str = ''
  for(let op of delta.ops){
    str += op.insert
  }
  return str.replace(/\s/g,"")
}
const textNumber = computed(() => detalTotext(editor.text).length)
const textRef = ref()


function submitTopic() {
  const text = detalTotext(editor.text);
  if (text.length > 20000) {
    ElMessage.warning('字数超出限制，无法发布主题！');
    return;
  }

  if (!editor.title) {
    ElMessage.warning('请填写标题！');
    return;
  }

  if (editor.type<0) {
    ElMessage.warning('请选择一个合适的帖子类型！');
    return;
  }
  props.submitClick(editor,()=>{emit('success')})


}
function handleTypeChange(selectedTypeName) {
  editor.selectedType = editor.types.find(type => type.id === selectedTypeName);

}
function handleTypeChange2(selectedType) {
  return editor.types.find(type => type.id === selectedType);
}



const editorOption = {
  modules: {
    toolbar: {
      container: [
        "bold", "italic", "underline", "strike", "clean",
        { color: [] }, { 'background': [] },
        { size: ["small", false, "large", "huge"] },
        { header: [1, 2, 3, 4, 5, 6, false] },
        { list: "ordered" }, { list: "bullet" }, { align: [] },
        "blockquote", "code-block", "image",
        { indent: '-1' }, { indent: '+1' }
      ],
      handlers: {
        'image': function () {
          QuillWatch.emit(this.quill.id)
        }
      }
    },
    imageResize: {
      modules: [ 'Resize', 'DisplaySize' ]
    },
    ImageExtend: {
      action: axios.defaults.baseURL + '/api/image/cache',
      name: 'file',
      size: 5,
      loading: true,
      accept: 'image/png, image/jpeg',
      response: (resp) => {
        if (resp.data) {
          return axios.defaults.baseURL + '/images/' + resp.data
        } else {
          return null
        }
      },
      methods: 'POST',
      headers: xhr => {
        xhr.setRequestHeader('Authorization', accessHeader().Authorization);
      },
      start: () => editor.uploading = true,
      success: () => {
        ElMessage.success('图片上传成功!')
        editor.uploading = false
      },
      error: () => {
        ElMessage.success('图片上传失败。请联系管理员!')
        editor.uploading = false
      }
    }
  }
}

</script>

<template>
  <div>
    <el-drawer :model-value="show"
               direction="btt"
               size="70%"
                @open="initEditor"
               :close-on-click-modal="false"
    @close="emit('close')">
    <template #title>
        <div>
         <div style="font-weight: bold;color: #181818">发表新的帖子</div>
          <div style="font-size: 12px">发表内容之前请先阅读社区规则</div>
        </div>
      </template>
      <div style="display: flex;gap: 10px">
        <div style="width: 180px">
          <el-select placeholder="请选择主题类型" v-model="editor.type"  @change="handleTypeChange"  v-loading="!editor.types.length">
            <el-option v-for="type in editor.types.filter(x => x.id>0)" :key="type.id"  :value="type.id" :label="type.name">
              <div>
                <color-dot :color=type.color></color-dot>
                <span style="margin-left: 10px">{{type.name}}</span>
              </div>
            </el-option>
          </el-select>
        </div>
        <div style="flex: 1">
          <el-input maxlength="30" placeholder="请输入帖子标题..." :prefix-icon="Edit" v-model="editor.title"></el-input>
        </div>
      </div>
      <div style="margin-top: 10px;font-size: 15px;color: gray">
        <color-dot  :color="editor.selectedType?editor.selectedType.color:'#656565'"></color-dot>
        <span style="margin-left: 7px">{{editor.selectedType ? editor.selectedType.des: '请选择上方的帖子类型'}}</span>
      </div>
      <div v-loading="editor.uploading" element-loading-text="正在上传图片，请稍后..." style="margin-top: 15px;height: 440px;overflow: hidden">
        <quill-editor ref="textRef" content-type="delta" :options="editorOption"  placeholder="今天想分享点什么呢?" v-model:content="editor.text"style="height: calc(100% - 45px)" >

        </quill-editor>
      </div>
      <div style="display: flex;justify-content: space-between;margin-top: 10px">
        <div style="color: gray;font-size: 14px" >当前字数：{{textNumber}} 最大支持200字</div>
        <div>
          <el-button type="primary" :icon="Check" @click="props.submitClick(editor,()=>{emit('success')})" >{{props.submitButton}}</el-button>
        </div>
      </div>

    </el-drawer>
  </div>
</template>

<style scoped>
:deep(.el-drawer){
  width: 800px;
  margin: auto;
  border-radius: 10px 10px 0 0;
}
:deep(.el-drawer__header){
  margin: 0;
}


</style>